package com.example.base.mvvm

import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.app.TimePickerDialog.OnTimeSetListener
import android.os.Bundle
import android.view.LayoutInflater
import android.widget.DatePicker
import android.widget.EditText
import android.widget.TimePicker
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import java.lang.reflect.ParameterizedType
import java.util.*


abstract class BaseActivity<VDB:ViewDataBinding,VM:BaseViewModel> : AppCompatActivity() {


    private val type by lazy {
        (javaClass.genericSuperclass as ParameterizedType)
            .actualTypeArguments
    }

    protected val binding by lazy {
        val clazz = type[0] as Class<VDB>
        val method = clazz.getMethod("inflate", LayoutInflater::class.java)
        method.invoke(null,layoutInflater)as VDB
    }

    protected val vm by lazy {
        val clazz = type[1] as Class<VM>
        ViewModelProvider(this)[clazz]
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        initView()
        initData()
    }

    abstract fun initView()

    abstract fun initData()

    fun showDateDialog(et:EditText) {
        val calendar = Calendar.getInstance()
        DatePickerDialog(this,object :DatePickerDialog.OnDateSetListener{
            override fun onDateSet(p0: DatePicker?, p1: Int, p2: Int, p3: Int) {
                val mon = if (p2 + 1 < 10) "0"+(p2+1) else p1 + 1
                val day = if (p3<10) "0"+p3 else p3
                et.setText("$p1-$mon-$day")
            }
        },calendar.get(android.icu.util.Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH)).show()
    }

    fun showTimeDialog(et: EditText) {
        val calendar = Calendar.getInstance()
        TimePickerDialog(this,object :OnTimeSetListener{
            override fun onTimeSet(p0: TimePicker?, p1: Int, p2: Int) {
                val h = if (p1<10) "0"+p1 else p1
                val m = if (p2<10) "0"+p2 else p2
                et.setText(" $h:$m:00")
            }
        },calendar.get(Calendar.HOUR_OF_DAY),calendar.get(Calendar.MINUTE),true).show()
    }
}